/*
 * @Author: LiYu
 * @Date: 2022-04-03 21:22:11
 * @LastEditors: LiYu
 * @LastEditTime: 2022-04-03 23:05:55
 * @Description: 游戏控制类
 */
import Food from "./food";
import ScorePane from "./score-pane";
import Snake from "./snake";



class GameControl {
  snake: Snake;
  food: Food;
  scorePane: ScorePane;

  // 蛇的移动方向
  direction = "";
  // 蛇移动步幅
  stride: number;
  // 蛇移动频率
  timeout = 200;
  // 游戏是否结束
  gameOver = false;

  constructor(stride: number = 10) {
    this.stride = stride;
    this.snake = new Snake();
    this.food = new Food();
    this.scorePane = new ScorePane();
    this.init();
  }

  init() {
    // 监听键盘事件
    document.addEventListener("keydown", this.keydownHandler.bind(this));
    this.run();
  }

  keydownHandler(event: KeyboardEvent) {
    // 改变蛇的运动方向
    this.direction = event.code;
  }

  // 蛇动
  run() {
    let x = this.snake.x;
    let y = this.snake.y;
    const { stride } = this;
    switch (this.direction) {
      case "ArrowUp":
      case "Up":
        y -= stride;
        break;
      case "ArrowDown":
      case "Down":
        y += stride;
        break;
      case "ArrowLeft":
      case "Left":
        x -= stride;
        break;
      case "ArrowRight":
      case "right":
        x += stride;
        break;
    }

    if(this.checkEat(x, y)) {
      console.log('eat');
      this.food.change();
      this.scorePane.addScore();
      this.snake.addBody();
    }
    
    try {
      this.snake.x = x;
      this.snake.y = y;
    } catch(err) {
      alert((err as any).message);
      this.gameOver = true;
    }

    // 判断游戏是否结束
    if (!this.gameOver) {
      const timeout = Math.max(
        this.timeout - (this.scorePane.level - 1) * 30,
        30
      );
      // 循环执行run控制蛇动
      setTimeout(this.run.bind(this), timeout);
    }
  }

  checkEat(x: number, y: number): boolean {
    return x === this.food.x && y === this.food.y;
  }
}

export default GameControl;


